package com.xxxx.server.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xxxx.server.service.IOssService;
import com.xxxx.server.utils.ConstantPropertiesUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhao
 * @since 2021-11-22
 */
@Service
public class IOssServiceServiceImpl implements IOssService {


    @Override
    public String uploadFileAvatar(MultipartFile file , String filePath) {
        // 工具类获取配置
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        if(StringUtils.isBlank(filePath)){
            filePath = "common/userface/";
        }

        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //设置图片名字  图片路径+当前时间+唯一标识码+文件后缀
            String fileName = filePath + System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + suffix;

            //参数一 桶名称
            //参数二 文件完整路径  aa/bb/test.jpg
            //参数三 上传文件输入流
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭 OSSClient
            ossClient.shutdown();

            //返回文件url
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
